package www.rlicker.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import www.rlicker.model.Memberships;
import www.rlicker.mybatis.Criteria;
import www.rlicker.mybatis.PageResult;
import www.rlicker.service.IMembershipsService;
import www.rlicker.utils.BaseController;
import www.rlicker.utils.JsonResult;
import www.rlicker.utils.StringUtil;

@Controller
@RequestMapping(value = "/memberships")
public class MembershipsController extends BaseController{

	@Autowired
	private IMembershipsService service;

	@RequestMapping(value = "/showlist")
	public String showList() {
		return "memberships/membershipsList";
	}

	@RequestMapping("/querypage")
	@ResponseBody
	public PageResult queryPage(HttpServletRequest request) {
		Criteria<Memberships> param = new Criteria<Memberships>();
		List<Map<String, Object>> list = service.queryPage(param);
		PageResult pageResult = new PageResult();
		pageResult.setRows(list);
		return pageResult;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public JsonResult delete(String id, String userName) {
		String ret = service.deleteById(id);
		JsonResult jr = JsonResult.newInstance();
		return ret == null ? jr.declareSuccess() : jr.declareFailure(ret);
	}
	
	@ResponseBody
	@RequestMapping(value="/insert" , method = { RequestMethod.POST })
	public JsonResult insert(String obj){
	  service.deleteAll();
	  JsonResult jr = JsonResult.newInstance();
	  JSONArray object = JSONArray.parseArray(obj);
	  String ret = null;
	  for (int j = 0; j < object.size(); j++) {
		  JSONObject object2 = JSONObject.parseObject(object.get(j).toString());
		  if (!StringUtil.isNullOrBlank(object2.getString("duration")) && !StringUtil.isNullOrBlank(object2.getString("integral"))) {
			  Memberships  memberships = new Memberships();
			  memberships.setId(getSeqNum());
			  memberships.setDuration(object2.getString("duration"));
			  memberships.setIntegral(object2.getString("integral"));
			  ret = service.insert(memberships);
		  }
	  }
	  return ret == null ? jr.declareSuccess() : jr.declareFailure(ret); 
	}

}
